/*
 * @(#)SaveXmlAction.java
 *
 *
 * ver 1.0 Oct 3, 2007 ggranum
 */
package org.testfire.agent.action;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Map;
import org.testfire.agent.AgentProperties;
import org.testfire.model.TestsetType;
import org.testfire.model.exception.CannotParseObjectException;
import org.testfire.util.DOM3XmlReader;
import org.testfire.util.DOM3XmlWriter;
import org.testfire.util.DomReader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Save an XML Testset to the local store.
 */
public class SaveAction extends Action
{
    public SaveAction()
    {
        super( false, new String[]{"testset_xml"}, new String[]{} );
    }

    public String perform( Map<String, String> params, Map<String, String[]> paramValues )
    {
        String xml = params.get( "testset_xml" );
        this.perform( xml );
        return "";
    }

    public void perform( TestsetType testset )
    {
        String packageStr = testset.getClassPackage();
        String testsetName = testset.getName();
        String userName = testset.getUserName();
        packageStr = packageStr.replace( '.', '/' );
        String saveFilePath = new StringBuilder().append( userName ).append( "/" )
            .append( packageStr ).append( "/" ).append( testsetName ).append( ".xml" ).toString();

        File saveFile = new File(
            AgentProperties.getInstance().getSaveDirectory(), saveFilePath );
        saveFile.getParentFile().mkdirs();
        File f = new File( System.getProperty( "user.dir" ) );
        f = new File( f, "resources/tomcat/webapps/ROOT/schema/base.xsd" );
        if(!f.exists()){
            throw new IllegalAccessError( "Could not find Schema file at " + f.getAbsolutePath() );
        }
        String[] schema = new String[1];
        try
        {
            schema[0] = f.getCanonicalPath();
        }
        catch ( IOException e )
        {
            schema[0] = "";
        }
        DOM3XmlWriter.writeOut( testset.getElement().getOwnerDocument(), saveFile, schema, true );
    }

    public void perform( String xml )
    {
        // parse the document into a testset.
        Document doc;
        String[] schema = {"http://localhost:9292/schema/base.xsd"};
        File f = new File( System.getProperty( "user.dir" ) );
        File schemaDir = new File(f, "resources/tomcat/webapps/ROOT/schema");
        f = new File( schemaDir, "base.xsd" );
        if(!f.exists()){
            throw new IllegalAccessError( "Could not find Schema file at " + f.getAbsolutePath() );
        }
        DOM3XmlReader.SchemaResolver[] resolvers = {
//            new DOM3XmlReader.SchemaResolver( "http://gettestfire.org/schema/base.xsd", f ),
//            new DOM3XmlReader.SchemaResolver( "http://gettestfire.org/schema/watij/Finders.xsd", new File(schemaDir, "watij/Finders.xsd") ),
//            new DOM3XmlReader.SchemaResolver( "http://gettestfire.org/schema/watij/HtmlFinder.xsd", new File(schemaDir, "watij/HtmlFinder.xsd") )
        };
        try
        {
            doc = DOM3XmlReader.getDocument( DomReader.createTempFileForXMLString( xml ), schema, resolvers );
        }
        catch ( IOException e )
        {
            e.printStackTrace();
            return;
        }
        Element de = doc.getDocumentElement();
        TestsetType testset;
        try
        {
            testset = new TestsetType( de );
        }
        catch ( CannotParseObjectException e )
        {
            e.printStackTrace();
            return;
        }
        this.perform( testset );
    }

    public void saveXml( File toFile, String xml ) throws IOException
    {
        ByteBuffer b = ByteBuffer.wrap( xml.getBytes() );
        RandomAccessFile outStream = new RandomAccessFile( toFile, "rw" );
        FileChannel outChan = outStream.getChannel();
        outChan.write( b );
        outChan.close();
        outStream.close();
    }


}

// eof: SaveXmlAction.java